package com.demo.accessibilitykeeper;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.Log;

/**
 * Description:
 * Author: dengpao
 * Date: 2025/9/19 15:40
 */
public class NetworkManager {


    private static final String TAG = "NetworkManager";

    /**
     * 尝试自动连接网络
     */
    public static boolean tryConnectNetwork(Context context) {
        Log.d(TAG, "🔄 ATTEMPTING_AUTO_NETWORK_CONNECTION");

        // 优先尝试开启WiFi
        if (enableWifi(context)) {
            Log.i(TAG, "✅ WiFi_ENABLED - Attempting to connect");
            return true;
        }

        // 如果WiFi不可用，尝试开启移动数据
        if (enableMobileData(context)) {
            Log.i(TAG, "✅ MOBILE_DATA_ENABLED - Attempting to connect");
            return true;
        }

        // 如果都无法开启，打开网络设置页面
        openNetworkSettings(context);

        return false;
    }

    /**
     * 开启WiFi
     */
    public static boolean enableWifi(Context context) {
        try {
            WifiManager wifiManager = (WifiManager) context.getApplicationContext()
                    .getSystemService(Context.WIFI_SERVICE);

            if (wifiManager == null) {
                Log.w(TAG, "❌ WIFI_MANAGER_UNAVAILABLE");
                return false;
            }

            // 检查WiFi是否已经开启
            if (wifiManager.isWifiEnabled()) {
                Log.d(TAG, "✅ WiFi_ALREADY_ENABLED");
                return true;
            }

            // 尝试开启WiFi（需要系统权限）
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                // Android 10+ 需要特殊处理
                return enableWifiAndroid10Plus(context);
            } else {
                // 旧版本Android可以直接开启
                boolean success = wifiManager.setWifiEnabled(true);
                Log.d(TAG, "🔧 WiFi_SET_ENABLED - Success: " + success);
                return success;
            }

        } catch (Exception e) {
            Log.e(TAG, "Error enabling WiFi", e);
            return false;
        }
    }

    /**
     * Android 10+ 开启WiFi的特殊处理
     */
    private static boolean enableWifiAndroid10Plus(Context context) {
        try {
            // Android 10+ 需要用户交互才能开启WiFi
            // 这里尝试通过面板开启
            Intent panelIntent = new Intent(Settings.Panel.ACTION_WIFI);
            panelIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(panelIntent);

            Log.d(TAG, "📱 OPENED_WIFI_PANEL_ANDROID_10_PLUS");
            return true;

        } catch (Exception e) {
            Log.e(TAG, "Error opening WiFi panel", e);
            return false;
        }
    }

    /**
     * 开启移动数据
     */
    public static boolean enableMobileData(Context context) {
        try {
            // 检查移动数据是否已经开启
            if (isMobileDataEnabled(context)) {
                Log.d(TAG, "✅ MOBILE_DATA_ALREADY_ENABLED");
                return true;
            }

            // 尝试开启移动数据（需要系统权限）
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                // Android 10+ 需要打开设置页面
                return openMobileDataSettings(context);
            } else {
                // 旧版本尝试通过反射开启（需要系统权限）
                return enableMobileDataLegacy(context);
            }

        } catch (Exception e) {
            Log.e(TAG, "Error enabling mobile data", e);
            return false;
        }
    }

    /**
     * 检查移动数据是否开启
     */
    private static boolean isMobileDataEnabled(Context context) {
        try {
            ConnectivityManager cm = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            if (cm == null) {
                return false;
            }

            NetworkInfo mobileInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            return mobileInfo != null && mobileInfo.isConnected();

        } catch (Exception e) {
            Log.e(TAG, "Error checking mobile data status", e);
            return false;
        }
    }

    /**
     * 旧版本Android开启移动数据（需要系统权限）
     */
    private static boolean enableMobileDataLegacy(Context context) {
        try {
            // 使用反射调用系统方法（需要系统权限）
            ConnectivityManager cm = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            if (cm == null) {
                return false;
            }

            java.lang.reflect.Method method = cm.getClass()
                    .getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
            method.setAccessible(true);
            method.invoke(cm, true);

            Log.d(TAG, "🔧 MOBILE_DATA_ENABLED_LEGACY");
            return true;

        } catch (Exception e) {
            Log.w(TAG, "Failed to enable mobile data via reflection", e);
            return false;
        }
    }

    /**
     * 打开移动数据设置页面
     */
    private static boolean openMobileDataSettings(Context context) {
        try {
            Intent intent = new Intent(Settings.ACTION_DATA_USAGE_SETTINGS);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);

            Log.d(TAG, "📱 OPENED_MOBILE_DATA_SETTINGS");
            return true;

        } catch (Exception e) {
            Log.e(TAG, "Error opening mobile data settings", e);
            return false;
        }
    }

    /**
     * 打开网络设置页面
     */
    public static void openNetworkSettings(Context context) {
        try {
            Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            // 尝试多种设置页面Intent
            try {
                context.startActivity(intent);
            } catch (Exception e) {
                // 备选方案
                intent = new Intent(Settings.ACTION_SETTINGS);
                context.startActivity(intent);
            }

            Log.d(TAG, "📱 OPENED_NETWORK_SETTINGS");

        } catch (Exception e) {
            Log.e(TAG, "Error opening network settings", e);
        }
    }

    /**
     * 检查是否有可用的网络连接
     */
    public static boolean isNetworkAvailable(Context context) {
        try {
            ConnectivityManager cm = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            if (cm == null) {
                return false;
            }

            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            return activeNetwork != null && activeNetwork.isConnectedOrConnecting();

        } catch (Exception e) {
            Log.e(TAG, "Error checking network availability", e);
            return false;
        }
    }

    /**
     * 获取当前网络类型
     */
    public static String getNetworkType(Context context) {
        try {
            ConnectivityManager cm = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            if (cm == null) {
                return "none";
            }

            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            if (activeNetwork == null || !activeNetwork.isConnectedOrConnecting()) {
                return "none";
            }

            switch (activeNetwork.getType()) {
                case ConnectivityManager.TYPE_WIFI:
                    return "wifi";
                case ConnectivityManager.TYPE_MOBILE:
                    return "mobile";
                case ConnectivityManager.TYPE_ETHERNET:
                    return "ethernet";
                case ConnectivityManager.TYPE_VPN:
                    return "vpn";
                default:
                    return "unknown";
            }

        } catch (Exception e) {
            Log.e(TAG, "Error getting network type", e);
            return "unknown";
        }
    }

    /**
     * 检查WiFi是否可用
     */
    public static boolean isWifiAvailable(Context context) {
        try {
            WifiManager wifiManager = (WifiManager) context.getApplicationContext()
                    .getSystemService(Context.WIFI_SERVICE);

            return wifiManager != null && wifiManager.isWifiEnabled();

        } catch (Exception e) {
            Log.e(TAG, "Error checking WiFi availability", e);
            return false;
        }
    }

    /**
     * 检查移动数据是否可用
     */
    public static boolean isMobileDataAvailable(Context context) {
        try {
            TelephonyManager tm = (TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);

            return tm != null && tm.getSimState() == TelephonyManager.SIM_STATE_READY;

        } catch (Exception e) {
            Log.e(TAG, "Error checking mobile data availability", e);
            return false;
        }
    }

}
